package com.ym.livedemo.live

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import com.ym.livedemo.Constant
import com.ym.livedemo.R
import com.ym.livedemo.SystemBarHelper
import com.ym.livedemo.api.BusinessViewModel
import com.ym.livedemo.databinding.ActivityAudienceBinding
import com.ym.livedemo.databinding.ActivityCreateLiveBinding
import com.ym.livedemo.loge
import com.ym.livedemo.utils.SPUtils
import com.ym.ymplayer.YMPlayerVideoActivity
import splitties.toast.toast

class AudienceActivity : AppCompatActivity() {
    private val viewModel by viewModels<BusinessViewModel>()
    private lateinit var viewBinding: ActivityAudienceBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = ActivityAudienceBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)
        SystemBarHelper.immersiveStatusBar(this, 0f)
        init()
        viewBinding.back.setOnClickListener { onBackPressed() }

        viewBinding.getLiveUrl.setOnClickListener {
            getLiveUrl()
        }

        viewBinding.watchLive.setOnClickListener {
            if (viewBinding.liveEdit.text.isBlank()) {
                toast("请先获取拉流地址")
                return@setOnClickListener
            }
            YMPlayerVideoActivity.start(this, viewBinding.liveEdit.text.toString())
        }
    }

    private fun init() {
        viewBinding.userIdEdit.setText(Constant.UID.toString())
    }

    private fun getLiveUrl() {
        if (viewBinding.userIdEdit.text.toString().isBlank()) {
            toast("请输入用户ID")
            return
        }
        Constant.UID = viewBinding.userIdEdit.text.toString().toInt()
        viewModel.login(
            mapOf(
                Pair("type", 3),
                Pair("username", Constant.USER_NAME),
                Pair("phone", Constant.PHONE),
                Pair("uid", Constant.UID),
                Pair("appKey", Constant.APP_KEY),
                Pair("appSecret", Constant.APP_SECRET),
            )
        ) {
            if (it.code == 0) {
                Constant.TOKEN = it.data.token
                Constant.TOKEN = it.data.token
                SPUtils.put(this@AudienceActivity, Constant.TOKEN_KEY, Constant.TOKEN)
                SPUtils.put(this@AudienceActivity, Constant.UID_KEY, Constant.UID)
                loge("用户TOKEN: ${Constant.TOKEN}")
                viewModel.getLivePullUrl(0) {
                    val url = "$it${Constant.TOKEN}"
                    loge("拉流地址: $url")
                    viewBinding.liveEdit.setText(url)
                }
            } else {
                toast(it.msg)
            }
        }
    }
}